package com.yh.workbill.login;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import com.yh.workbill.App;
import com.yh.workbill.R;
import com.yh.workbill.base.BaseActivity;
import com.yh.workbill.databinding.ActivityLoginBinding;
import com.yh.workbill.db.UserInfo;
import com.yh.workbill.db.UserInfoDao;
import com.yh.workbill.login.mvp.LoginPresenter;
import com.yh.workbill.login.mvp.LoginView;
import com.yh.workbill.ui.MainActivity;
import com.yh.workbill.utils.Config;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.arch.core.executor.ArchTaskExecutor;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

public class LoginActivity extends BaseActivity implements LoginView {
    private ActivityLoginBinding binding;
    private LoginViewModel viewModel;
    private LoginPresenter presenter;
    private UserInfoDao userInfoDao;

    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int PERMISSION_CODE = 1000;
    private ArrayList<String> deniedPermission = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CODE) {
            deniedPermission.clear();
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                int result = grantResults[i];
                if (result != PackageManager.PERMISSION_GRANTED) {
                    deniedPermission.add(permission);
                }
            }

            if (deniedPermission.isEmpty()) {
                checkLogin();
            } else {
                new AlertDialog.Builder(this)
                        .setMessage("请把权限全部授权成功")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                LoginActivity.this.finish();
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String[] denied = new String[deniedPermission.size()];
                                ActivityCompat.requestPermissions(LoginActivity.this, deniedPermission.toArray(denied), PERMISSION_CODE);
                            }
                        }).create().show();
            }
        }
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_login);
    }

    @Override
    public void initJetPack(@Nullable Bundle savedInstanceState) {
        viewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        binding.setData(viewModel);
        binding.setLifecycleOwner(this);
    }

    @Override
    public void initObserve(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void initBaseSetting(@Nullable Bundle savedInstanceState) {
        presenter = new LoginPresenter(this);
        //把当前的prensenter绑定到lifecycle中销毁view
        LoginActivity.this.getLifecycle().addObserver(presenter);
        userInfoDao = App.appDataBase.getUserInfoDao();
        binding.btnLogin.setEnabled(false);
        binding.etPhone.addTextChangedListener(textWatcher);
        binding.etPwd.addTextChangedListener(textWatcher);
    }

    @Override
    public void initClick(@Nullable Bundle savedInstanceState) {
        binding.btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = viewModel.phone.getValue();
                String pwd = viewModel.pwd.getValue();
                presenter.loginPresenter(userInfoDao, phone, pwd);
            }
        });
    }

    @Override
    public void initDefaultMethod(@Nullable Bundle savedInstanceState) {

    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    //检测是否需要登录
    private void checkLogin() {
        SharedPreferences sf = getSharedPreferences(Config.SP_USER, MODE_PRIVATE);
        String phone = sf.getString("phone", "");
        if (phone != null && !phone.equals("")) {
            ArchTaskExecutor.getIOThreadExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    UserInfo singleUserInfo = userInfoDao.getSingleUserInfo(phone);
                    ArchTaskExecutor.getMainThreadExecutor().execute(() -> presenter.checkTokenPresenter(singleUserInfo.getToken()));
                }
            });
        }

    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String phone = binding.etPhone.getText().toString().trim();
            viewModel.phone.setValue(phone);
            String pwd = binding.etPwd.getText().toString().trim();
            viewModel.pwd.setValue(pwd);
            binding.btnLogin.setEnabled((!phone.isEmpty() && phone.length() == 11) && (!pwd
                    .isEmpty() && pwd.length() >= 6));
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (textWatcher != null) {
            textWatcher = null;
        }
    }

    @Override
    public void gonext() {
        Intent i = new Intent(LoginActivity.this, MainActivity.class);
        startActivity(i);
        finish();
    }

    @Override
    public void showTasot(String message) {
        if (!message.equals("")) {
            Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void showDialog(String content, boolean isCancelable) {
        showLoaddingDialog(content, isCancelable);
    }

    @Override
    public void hideDialog() {
        hideLoaddingDialog();
    }

}

